<template>
  <page-card title="应用管理">
    <div>
      <a-form layout="inline">
        <a-row style="height:56px">
          <a-col :span="8">
            <!-- <a-form-item> -->
            <a-space size="small">
              <slot name="buttons" />
              <template v-if="!$slots.buttons">
                <a-button v-if="hasPermission('add')"
                          style="margin-right:2px;"
                          type="primary"
                          action
                          icon="plus"
                          @click="appAdd()">新增应用</a-button>
              </template>
              <template v-if="!$slots.buttons">
                <a-button v-if="hasPermission('class')"
                          style="margin-right:2px;"
                          type="primary"
                          action
                          icon="plus"
                          @click="appClass()">应用分类</a-button>
              </template>
            </a-space>
          </a-col>
          <a-col :span="16"
                 style="text-align: right;">
            <!-- <a-form-item labelAlign="right"> -->
            <a-input-search style="width:240px"
                            v-model="queryParam.keyword"
                            placeholder="请输入应用名称、应用代码"
                            allowClear
                            @search="search" />
            <!-- </a-form-item> -->

          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-table :pagination="pagination"
             @change="handleTableChange"
             ref="table"
             :rowKey="(record, index) => index"
             :data-source="dataSource"
             :columns="columns">

      <template slot="name"
                slot-scope="text,record">
        <span v-text="record.name"
              class="app-name"></span>
      </template>
      <template slot="mssotype"
                slot-scope="text,record">
        <span v-text="record.mssotype == '1' ? '令牌' : '模拟登录'"></span>
      </template>
      <template slot="logo"
                slot-scope="item,record">
        <img class="app-logo"
             v-if="record.logo && record.logo.indexOf('/')>-1"
             :src="storage.baseURL+record.logo" />
        <div v-if="record.logo && record.logo.indexOf('/')==-1"
             :style="'background:' + (record.logoColor || '#0089ff')"
             class="icon-box">
          <span :class="record.logo"
                style="color:#fff"
                class="iconfont" />
        </div>
        <img class="app-logo"
             v-if="!record.logo"
             :src="defaultImg">
      </template>
      <template slot="category"
                slot-scope="item,record">
        <div v-if="record.category == '1'">本地应用</div>
        <div v-if="record.category == '2'">第三方</div>
      </template>

      <span slot="status"
            :style="{color:statusCell[record.status].color}"
            slot-scope="text, record">{{ statusCell[record.status].text }}</span>
      <template slot="operation"
                slot-scope="text, record">
        <a v-if="hasPermission('edit')"
           @click="appEdit(record)">编辑</a>
        <a-divider type="vertical"
                   v-if="hasPermission('edit')" />
        <a @click="appApi(record)">接口授权</a>
      </template>
    </a-table>

    <a-modal v-model="modalUnitVisible"
             :title="modalUnitTitle"
             ok-text="保存"
             cancel-text="取消"
             @ok="saveUnit">
      <div class="border">
        <a-input-search v-model="unitSearch"
                        @search="findSearch"
                        style="margin-bottom: 10px;">
        </a-input-search>

        <a-table v-if="!showtree"
                 :row-selection="{ selectedRowKeys: checkedKeysUnit.checked, onChange: onSelectChange}"
                 bordered
                 @change="searchTableChange"
                 ref="unitTableList"
                 :showHeader="false"
                 :pagination="unitpagination"
                 :rowKey="(record, index) => record.id"
                 :data-source="unitdata"
                 :columns="unitcolumns">
          <template slot="cfullName"
                    slot-scope="text,record"
                    :algin="left">
            <span v-if="record.parentName">{{ record.parentName }}<span>&nbsp;/&nbsp;</span></span>{{ record.name }}
          </template>
        </a-table>

        <a-tree v-if="showtree"
                @check="checkUnit"
                @select="selectUnit"
                @expand="expand"
                v-model="checkedKeysUnit"
                :selectedKeys="selectedKeys"
                :checkStrictly="checkStrictly"
                :expandedKeys="expandedKeys"
                checkable
                :showIcon="true"
                :tree-data="treeDataUnit">
          <a-icon slot="switcherIcon"
                  type="caret-down" />
          <a-icon slot="clazz"
                  type="appstore" />
          <a-icon slot="unit"
                  type="home" />
          <a-icon slot="dept"
                  type="bank" />
          <template slot="custom"
                    slot-scope="item">
            <span>{{ item.treeTitle }} </span>
            <span v-if="!item.isLeaf">
              <span v-if="!item.checked"
                    title="全选">
                <a-icon type="plus-square"
                        @click="addClick(item)" />
              </span>
              <span v-else
                    title="取消全选">
                <a-icon type="minus-circle"
                        @click="cancelClick(item)" />
              </span>
            </span>

          </template>
        </a-tree>
      </div>
    </a-modal>

    <a-modal v-model="modalApiVisible"
             :title="modalApiTitle"
             ok-text="保存"
             cancel-text="取消"
             @ok="saveApi">
      <div class="border">
        <a-tree v-if="modalApiVisible"
                @check="checkApi"
                v-model="checkedKeysApi"
                checkable
                :tree-data="treeDataApi" />
      </div>
    </a-modal>
  </page-card>
</template>

<script>
import { PAGINATION, TABLE_STATUS_CELL } from '../../constants'
import defaultImg from '../../assets/app-default.png'
import { storage } from '@zh/common-utils/http'
import {
  queryApiTree,
  page,
  queryUnit,
  queryApi,
  saveUnit,
  saveApi
} from '../../api/application/index'
import { unitTreeV2 } from '../../api/unit/index'
import { unitpage } from '../../api/user/index'
export default {
  data () {
    return {
      storage,
      defaultImg: defaultImg,
      unitdata: [],
      showtree: true,
      unitSearch: '',
      expandedKeys: [],
      selectedKeys: [],
      checkStrictly: true,
      appId: '',
      pagination: {
        current: 1,
        total: 0,
        // 默认每页显示10条数据
        pageSize: 10,
        showSizeChanger: true,
        // 修改每页显示条数
        pageSizeOptions: ['10', '20', '50', '100'],
        // 总数据数量
        showTotal: (total) => `共 ${total} 条数据`
      },
      unitpagination: {
        current: 1,
        total: 0,
        // 默认每页显示10条数据
        pageSize: 10,
        showSizeChanger: true,
        // 修改每页显示条数
        pageSizeOptions: ['10', '20', '50', '100'],
        // 总数据数量
        showTotal: (total) => `共 ${total} 条数据`
      },
      statusCell: TABLE_STATUS_CELL,
      treeDataUnit: [],
      checkedKeysUnit: {
        checked: [],
        halfChecked: []
      },
      modalUnitVisible: false,
      modalUnitTitle: '',
      treeDataApi: [],
      checkedKeysApi: [],
      modalApiVisible: false,
      modalApiTitle: '',
      fieldsUnit: {
        children: 'children',
        title: 'treeTitle',
        key: 'key'
      },
      dataSource: [],
      columns: [
        {
          title: '应用图标',
          dataIndex: 'logo',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'logo' }
        },
        {
          title: '应用名称',
          dataIndex: 'name',
          flex: 1,
          align: 'center'
        },
        {
          title: '应用代码',
          dataIndex: 'code',
          align: 'center'
        },
        {
          title: '应用类型',
          dataIndex: 'category',
          align: 'center',
          scopedSlots: { customRender: 'category' }
        },
        {
          title: '应用分类',
          dataIndex: 'appClassificationName',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'appClassificationName' }
        },
        {
          title: '排序号',
          dataIndex: 'orderNo',
          align: 'center',
          width: '80px'
        },
        {
          title: '单点登录方式',
          dataIndex: 'mssotype',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'mssotype' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          align: 'center',
          width: '100px',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '136px',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      unitcolumns: [
        {
          title: '机构名称',
          dataIndex: 'name',
          align: 'left',
          ellipsis: true,
          scopedSlots: { customRender: 'cfullName' }
        }
      ],
      queryParam: {
        keyword: ''
      }
    }
  },
  activated () {
    this.load()
  },
  methods: {
    setDefaultImg (event) {
      const img = event.srcElement
      img.src = this.defaultImg
      img.onerror = null
    },
    appClass () {
      this.$router.push({
        path: '/application/manage/class'
      })
    },
    load (params = {}) {
      this.queryParam.currPage = this.pagination.current
      this.queryParam.pageSize = this.pagination.pageSize
      // page(this.queryParam).then((res) => {
      //   // this.dataSource = res.list
      //   this.dataSource = []
      //   let arr = []
      //   res.list.forEach((item) => {
      //     arr.push(item)
      //   })
      //   this.dataSource = arr
      //   this.pagination.current = res.currPage
      //   this.pagination.total = res.totalCount
      // })
      page({ ...this.queryParam }).then((response) => {
        this.dataSource = response.list
        this.pagination.current = response.currPage
        this.pagination.total = response.totalCount
        this.pagination.pageSize = response.pageSize
      })
    },
    appAdd () {
      this.$router.push({
        path: '/application/manage/edit'
      })
    },
    appApi (record) {
      this.modalApiVisible = true
      this.modalApiTitle = '接口授权'
      this.checkedKeysApi = []
      this.treeDataApi = []
      this.appId = record.id
      this.getCheckedKeysApi()
      this.initTreeApi()
    },
    appUnit (record) {
      this.$router.push({ path: 'unit?id=' + record.id })
      // let topId
      // const loginUser = this.$store.getLoginUser()
      // if (loginUser.account === 'admin') {
      //   topId = 0
      // } else {
      //   topId = loginUser.depts[0].deptId
      // }
      // this.modalUnitVisible = true
      // this.showtree = true
      // this.unitSearch = ''
      // this.modalUnitTitle = '机构授权'
      // this.checkedKeysUnit.checked = []
      // this.expandedKeys = []
      // this.treeDataUnit = []
      // this.appId = record.id
      // this.getCheckedKeys()
      // this.initTree(topId)
    },
    initTree (topId) {
      unitTreeV2(topId).then((response) => {
        this.treeDataUnit = response
        this.treeDataUnit.forEach((item) => {
          this.setTreeData(item)
        })
      })
    },
    setTreeData (item) {
      item.scopedSlots = {
        title: 'custom',
        icon: 'icon'
      }
      let children = item.children
      if (children && children.length > 0) {
        children.forEach((data) => {
          this.setTreeData(data)
        })
      }
    },
    getCheckedKeys () {
      queryUnit(this.appId).then((response) => {
        if (response.length > 0) {
          response.forEach((item) => {
            this.expandedKeys.push(item.parentId)
            this.checkedKeysUnit.checked.push(item.unitId)
          })
        }
      })
    },
    appEdit (record) {
      this.$router.push({
        path: '/application/manage/edit',
        query: {
          id: record.id
        }
      })
    },
    getCheckedKeysApi () {
      queryApi(this.appId).then((response) => {
        if (response.length > 0) {
          response.forEach((item) => {
            if (item.openApiId != '0') {
              this.checkedKeysApi.push(item.openApiId)
            }
          })
        }
      })
    },
    initTreeApi () {
      queryApiTree('JKFL').then((response) => {
        this.treeDataApi = response
      })
    },
    search () {
      this.pagination.current = 1
      this.load()
    },
    handleTableChange (pagination) {
      this.pagination = pagination
      this.load()
    },
    searchTableChange (pagination) {
      this.unitpagination = pagination
      this.unitpagination.currPage = pagination.current
      this.unitpagination.name = this.unitSearch
      this.searchTree()
    },
    saveUnit () {
      saveUnit(this.appId, this.checkedKeysUnit.checked).then((response) => {
        // this.message.info('保存成功')
        this.modalUnitVisible = false
      })
    },
    saveApi () {
      saveApi(this.appId, this.checkedKeysApi).then((response) => {
        // this.message.info('保存成功')
        this.modalApiVisible = false
      })
    },
    checkUnit (checkedKeys, e) {
      this.checkedKeysUnit.checked = checkedKeys.checked
    },
    selectUnit (selectedKeys, info) {
      // let selectData = info.node.dataRef
      // if (this.checkedKeysUnit.checked.indexOf(selectData.key) >= 0) {
      //   this.getClick(selectData, 'del')
      // } else {
      //   this.getClick(selectData, 'add')
      // }
      // this.selectedKeys = selectedKeys
    },
    expand (expandedKeys, info) {
      // let data = info.node.dataRef
      // if (info.expanded) {
      //   expandedKeys = this.getExpanded(expandedKeys, data, 'add')
      // } else {
      //   expandedKeys = this.getExpanded(expandedKeys, data, 'del')
      // }

      this.expandedKeys = expandedKeys
    },
    getExpanded (expandedKeys, data, type) {
      if (type === 'add') {
        if (expandedKeys.indexOf(data.key) === -1) {
          expandedKeys.push(data.key)
        }
      } else {
        if (expandedKeys.indexOf(data.key) >= 0) {
          expandedKeys = expandedKeys.filter((k) => k !== data.key)
        }
      }
      let children = data.children
      if (children && children.length > 0) {
        children.forEach((item) => {
          expandedKeys = this.getExpanded(expandedKeys, item, type)
        })
      }
      return expandedKeys
    },
    addClick (item) {
      this.getClick(item, 'add')
    },
    cancelClick (item) {
      this.getClick(item, 'del')
      this.selectedKeys = []
    },
    getClick (data, type) {
      if (type === 'add') {
        if (this.checkedKeysUnit.checked.indexOf(data.key) === -1) {
          if (data.disabled === false) {
            this.checkedKeysUnit.checked.push(data.key)
          }
        }
        const addchildren = data.children
        if (addchildren && addchildren.length > 0) {
          for (let i = 0; i < addchildren.length; i++) {
            const addData = addchildren[i]
            this.getClick(addData, 'add')
          }
        }
      } else {
        if (this.checkedKeysUnit.checked.indexOf(data.key) >= 0) {
          if (data.disabled === false) {
            this.checkedKeysUnit.checked = this.checkedKeysUnit.checked.filter(
              (k) => k !== data.key
            )
          }
        }
        const delchildren = data.children
        if (delchildren && delchildren.length > 0) {
          for (let i = 0; i < delchildren.length; i++) {
            const delData = delchildren[i]
            this.getClick(delData, 'del')
          }
        }
      }
    },
    findSearch () {
      if (this.unitSearch) {
        this.showtree = false
      }
      this.showtree = false
      this.unitpagination.currPage = 1
      this.unitpagination.name = this.unitSearch
      this.searchTree()
    },
    searchTree () {
      // if (this.unitSearch) {
      //   this.showtree = false
      // }
      // this.showtree = false
      // this.unitpagination.current = 1
      // this.unitpagination.name = this.unitSearch
      unitpage(this.unitpagination).then((response) => {
        if (response.list) {
          let i = 0
          for (i; i < response.list.length; i++) {
            const unit = response.list[i]
            for (const item in unit) {
              if (item === 'children') {
                delete unit[item]
              }
            }
          }
        }
        this.unitdata = response.list
        this.unitpagination.current = response.currPage
        this.unitpagination.total = response.totalCount
      })
    },
    checkApi (checkedKeys, e) {
      this.checkedKeysApi = []
      const list = e.checkedNodes
      list.forEach((item) => {
        const data = item.data.props.dataRef
        if (data.type === '2') {
          this.checkedKeysApi.push(data.key)
        }
      })
    },
    onSelectChange (selectedRowKeys) {
      this.checkedKeysUnit.checked = selectedRowKeys
    }
  },
  watch: {
    unitSearch (newVal, oldVal) {
      if (newVal == '') {
        this.showtree = true
      }
    }
  }
}
</script>

<style scoped >
.icon-box {
  display: inline-block;
  width: 50px;
  height: 50px;
  border-radius: 4px;
}
.iconfont {
  height: 50px;
  display: flex;
  font-size: calc(var(--font-size-20) + 17px);
  justify-content: center;
  align-items: center;
}
.app-logo {
  width: 50px;
  height: 50px;
  border: 0;
  border-radius: 5px;
}
.border {
  max-height: 500px;
  overflow-y: auto;
}
.ant-form-inline .ant-form-item {
  margin: right 0px !important;
}
.app-name {
  min-width: 150px;
}
</style>
